// import { ref, reactive, getCurrentInstance } from "vue";
// const { proxy } = getCurrentInstance() as any;
/**打开数据库 */
import Dexie from "dexie";
let db: any;
let userName: string;
const openDatabase = async (
  databaseName: string,
  version: number = 1,
  name: string = "",
  keyPath: string = "QuestionUserId"
) => {
  try {
    /**本地存的账号版本 */
    let oldData: any;
    // if (localStorage.getItem(databaseName)) {

    // }
    oldData = JSON.parse(localStorage.getItem(databaseName) || "");
    oldData.version = oldData.version > version ? oldData.version : version;
    // else {
    //   oldData = {
    //     version: 1,
    //     ...oldData,
    //   };
    // }
    localStorage.setItem(databaseName, JSON.stringify(oldData));
    console.log("版本号：", oldData.version);
    const request = indexedDB.open(databaseName, oldData.version);
    return new Promise((resolve, reject) => {
      request.onerror = (event: any) => {
        reject(event.target.error);
      };
      request.onsuccess = (event: any) => {
        db = event.target.result;
        console.log("打开数据库成功", databaseName, db);
        userName = databaseName;
        resolve(db);
      };
      request.onupgradeneeded = (event: any) => {
        const database = event.target.result;
        if (name != "") {
          console.log(name, keyPath);

          if (!database.objectStoreNames.contains(name)) {
            database.createObjectStore(name, { keyPath: keyPath });
          } else {
            console.log("有了");
          }
        }
      };
    });
  } catch (error) {
    console.error("数据库打开错误", error);
    throw error;
  }
};
/**整体检验并存储数据 */
const saveAllChatMessage = async (
  list: any[],
  tableName: string,
  keyPath: string = "QuestionUserId"
) => {
  try {
    if (!db) {
      db = await openDatabase(userName);
    }
    list.forEach((item, i) => {
      const transaction = db.transaction([tableName], "readonly");
      const objectStore = transaction.objectStore(tableName);
      const request = objectStore.get(item[keyPath]);
      return new Promise<void>((resolve, reject) => {
        request.onerror = (event: any) => {
          reject(event.target.error);
        };
        request.onsuccess = async (event: any) => {
          if (event.target.result) {
            console.log("已存在当前(" + item.SendUserName + ")用户数据");
            resolve();
          } else {
            const transaction = db.transaction([tableName], "readwrite");
            const objectStore = transaction.objectStore(tableName);
            const request = objectStore.add({ list: [], ...item });
            return new Promise<void>((resolve, reject) => {
              request.onerror = (event: any) => {
                reject(event.target.error);
              };
              request.onsuccess = () => {
                resolve();
              };
            });
          }
        };
      });
    });

    // const transaction = db.transaction([tableName], "readwrite");
    // const objectStore = transaction.objectStore(tableName);
    // const request = objectStore.put(message);
    // return new Promise<void>((resolve, reject) => {
    //   request.onerror = (event: any) => {
    //     reject(event.target.error);
    //   };
    //   request.onsuccess = () => {
    //     resolve();
    //   };adadadad
    // });
  } catch (error) {
    console.error("对象存储错误", error);
    throw error;
  }
};
/**存储数据 */
const saveChatMessage = async (message: any, tableName: string) => {
  try {
    if (!db) {
      db = await openDatabase(userName);
    }
    const transaction = db.transaction([tableName], "readwrite");
    const objectStore = transaction.objectStore(tableName);
    console.log(message);

    const request = objectStore.put(message);
    return new Promise<void>((resolve, reject) => {
      request.onerror = (event: any) => {
        reject(event.target.error);
      };
      request.onsuccess = () => {
        resolve();
      };
    });
  } catch (error) {
    console.error("对象存储错误", error);
    throw error;
  }
};
/**获取数据 */
const getChatHistory = async (userName: string, tableName: string) => {
  try {
    if (!db) {
      db = await openDatabase(userName);
    }
    console.log(tableName);

    const transaction = db.transaction([tableName], "readonly");
    const objectStore = transaction.objectStore(tableName);
    const request = objectStore.get(userName);
    return new Promise((resolve, reject) => {
      request.onerror = (event: any) => {
        reject(event.target.error);
      };
      request.onsuccess = (event: any) => {
        console.log(event.target.result);

        resolve(event.target.result);
      };
    });
  } catch (error) {
    console.error("对象读取错误", error);
    throw error;
  }
};
// /**新建表 */
const createNewObjectStore = async (
  list: any[],
  name: string,
  keyPath: string = "QuestionUserId"
) => {
  try {
    const examine = async () => {
      if (!db) {
        setTimeout(() => {
          examine();
        }, 500);
      } else {
        let oldData: any = JSON.parse(localStorage.getItem(userName) || "");
        let version: number = oldData.version;
        for (let index = 0; index < list.length; index++) {
          // db = await openDatabase(userName);

          version = version + 1;
          // version++;

          if (!db.objectStoreNames.contains(list[index][name])) {
            db.close();
            await openDatabase(userName, version, list[index][name], keyPath);
          } else {
            // console.log("已存在");
          }

          // if (!db.objectStoreNames.contains(list[index][name])) {
          //   db.createObjectStore(list[index][name], { keyPath: keyPath });
          // } else {
          //   console.log("有了");
          // }
        }
      }
    };
    examine();
  } catch (error) {
    console.error("创建新对象存储错误", error);
    throw error;
  }
};
const deleteDatabase = async (name: string) => {
  await db.close();
  Dexie.delete(name);
};
export {
  openDatabase,
  saveChatMessage,
  getChatHistory,
  createNewObjectStore,
  saveAllChatMessage,
  deleteDatabase,
};
